package com.leizhi.demo.monitor.achieve;

import com.leizhi.demo.monitor.achieve.listener.RtpHandlerListener;
import com.leizhi.demo.monitor.achieve.listener.TcpRtpDecoderListener;
import com.leizhi.demo.monitor.achieve.listener.UdpRtpDecoderListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description RTP 服务
 * @Version 1.0.0-SNAPSHOT
 * @Author leizhi
 * @Date 2025/4/27 10:05
 */
public class RtpService {

    private static final Logger logger = LoggerFactory.getLogger(RtpService.class);
    // 定义 AttributeKey 用于存储 ssrc
    public static final AttributeKey<Long> ATTR_KEY_SSRC = AttributeKey.valueOf("ssrc");

    /* 单例模式 */
    private static RtpService instance;
    private Bootstrap udpBootstrap;


    private RtpService(PushStreamService pushStreamService, Integer tcpPort, String pushRtmpAddress) {
        udpInstance(pushStreamService, pushRtmpAddress);
        tcpInstance(pushStreamService, pushRtmpAddress, tcpPort);
    }

    private void udpInstance(PushStreamService pushStreamService, String pushRtmpAddress) {
        EventLoopGroup group = new NioEventLoopGroup();
        this.udpBootstrap = new Bootstrap();
        this.udpBootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 3)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new UdpRtpDecoderListener());
                        pipeline.addLast(new IdleStateHandler(15, 0, 0));
                        pipeline.addLast(new RtpHandlerListener(pushStreamService, pushRtmpAddress));
                    }
                });
    }

    private void tcpInstance(PushStreamService pushStreamService, String pushRtmpAddress, Integer tcpPort) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap tcpBootstrap = new ServerBootstrap();
        tcpBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_RCVBUF, 1024 * 1024 * 3)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new TcpRtpDecoderListener());
                        pipeline.addLast(new IdleStateHandler(15, 0, 0));
                        pipeline.addLast(new RtpHandlerListener(pushStreamService, pushRtmpAddress));
                    }
                });
        try {
            ChannelFuture future = tcpBootstrap.bind(tcpPort).sync();
            if (!future.isSuccess()) {
                throw new RuntimeException(future.cause());
            }
            logger.info("TCP RTP 服务启动成功，监听端口：{}", tcpPort);
        } catch (InterruptedException e) {
            throw new RuntimeException("TCP RTP 服务启动失败：" + e.getMessage(), e);
        }
    }

    public static void setInstance(PushStreamService pushStreamService, Integer tcpPort, String pushRtmpAddress) {
        if (instance == null) {
            instance = new RtpService(pushStreamService, tcpPort, pushRtmpAddress);
        }
    }

    public static RtpService getInstance() {
        if (instance != null) {
            return instance;
        }
        throw new RuntimeException("RtpService is not init");
    }

    /* 开启设备推流的UDP通道 */
    public Channel udpStart(Long ssrc, Integer port) {
        try {
            ChannelFuture future = this.udpBootstrap.bind(port).sync();
            if (!future.isSuccess()) {
                throw new RuntimeException(future.cause());
            }

            Channel channel = future.channel();
            channel.attr(ATTR_KEY_SSRC).set(ssrc);
            logger.info("SSRC-{}：UDP RTP 服务启动成功，端口[{}]", ssrc, port);
            return channel;
        } catch (InterruptedException e) {
            logger.error("SSRC-{}：UDP RTP 服务启动失败，端口[{}]，错误信息：{}", ssrc, port, e.getMessage());
            throw new RuntimeException("UDP RTP 服务启动失败");
        }
    }

}
